package cn.semyes.simi.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import cn.semyes.simi.bean.SmsConstants;
import cn.semyes.simi.entity.YuanshengSimiEntity;
import cn.semyes.simi.service.YuanshengSimiService;
import cn.semyes.simi.util.AjaxJson;
import cn.semyes.simi.util.BusinessUtils;
import cn.semyes.simi.util.ContextHolderUtils;

@RestController
@RequestMapping("simi/yuanshengSimi.do")
public class YuanshengSimiController {
	
	private String message = null;
	private boolean flag = false;
	
	private String token = null;
	private String mobile = null;
	private String templateType = null;
	private String appName = null;
	private AjaxJson aj;
	private Long baiduappstarttime;
	private Long baiduappcurrenttime;
	private HttpSession session;
	private List<YuanshengSimiEntity> yishengSmsTmplEntities = null;
	private String randomCode = null;
	private String content = null;
	private String returnStatus = null;
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private YuanshengSimiService yuanshengSimiService;
	
	/**
	 * 发送短信,60秒间隔
	 * 
	 * @return
	 * 
	 */
	@RequestMapping(params = "sendBaiduAppSms")
	@ResponseBody
	public AjaxJson doBaiduAppSendMsg(HttpServletRequest request) {
		token = request.getHeader("Authorization");
		mobile = request.getParameter("mobile_num") == null ? "" : request.getParameter("mobile_num").trim();
		templateType = request.getParameter("type");
		appName = request.getParameter("appname");
		logger.info("------" + appName + "请求进来-----");
		aj = new AjaxJson();
		
		if(!SmsConstants.YUANSHENG_APP_SMS_TOKEN.equals(token)){
			message = "you have no permit to login";
			aj.setMsg(message);
			aj.setSuccess(false);
			return aj;
		}
		
		// 判断手机是否合法并去除空格
		if ("".equals(mobile)) {
			message = "please insert mobile num";
			flag = false;
			aj.setMsg(message);
			aj.setSuccess(flag);
			return aj;
		}
		if (!BusinessUtils.isMobileNO(mobile)) {
			message = "please insert correct mobile";
			flag = false;
			aj.setMsg(message);
			aj.setSuccess(flag);
			return aj;
		}
		
		message = "send success";
		flag = true;

		baiduappstarttime = null; // 存储上次的短信发送时间
		baiduappcurrenttime = System.currentTimeMillis();// 当前发送时间
		session = ContextHolderUtils.getSession();

		// 把发送时间放到session里
		if (null == session.getAttribute("baiduappstarttime") || session.getAttribute("baiduappstarttime").equals("")) {
			baiduappstarttime = System.currentTimeMillis();
			session.setAttribute("baiduappstarttime", baiduappstarttime);
			session.setAttribute("baiduappfirstsend", true);
			session.setMaxInactiveInterval(1800);

		} else {

			baiduappstarttime = (Long) session.getAttribute("baiduappstarttime");

			session.removeAttribute("baiduappfirstsend");

			session.setAttribute("baiduappfirstsend", false);

			// System.out.println(starttime);
		}
		// 对上一次发送时间与当前发送时进行比较
		if ((boolean) session.getAttribute("baiduappfirstsend") || baiduappcurrenttime - baiduappstarttime > 59000) {

			session.setAttribute("baiduappstarttime", baiduappcurrenttime);// 时间间隔达到要求则把当前时间设为上一次发送时间			
			
			// 判断模板类型,并查询模板
			if (SmsConstants.SMS_YUANSHENG_APP_REGISTER.equals(templateType)) {

				yishengSmsTmplEntities = yuanshengSimiService.getYishengSmsTmplEntity(SmsConstants.SMS_YUANSHENG_APP_REGISTER,SmsConstants.SMS_ISUSED_YES);

			} else if (SmsConstants.SMS_YUANSHENG_APP_LOGIN.equals(templateType)) {

				yishengSmsTmplEntities = yuanshengSimiService.getYishengSmsTmplEntity(SmsConstants.SMS_YUANSHENG_APP_LOGIN,SmsConstants.SMS_ISUSED_YES);
			}
			
			// 若有短信模板则继续发送
			if (yishengSmsTmplEntities != null && yishengSmsTmplEntities.size() > 0) {
				content = yishengSmsTmplEntities.get(0).getSmsContent() == null ? ""
						: yishengSmsTmplEntities.get(0).getSmsContent();
				if (content.indexOf("{验证码}") == -1  && content.indexOf("{原昇科技应用}") == -1) {
					message = "invalid format";
					flag = false;
				} else {
					randomCode = BusinessUtils.createRandom(true, 6);

					content = content.replace("{验证码}", randomCode);
					content = content.replace("{原昇科技应用}", appName);			
					
					// 发送短信
					try {

						returnStatus = BusinessUtils.sendAndReturnMsg(mobile, content, true, "", "");
						if (returnStatus != null && returnStatus.indexOf(",") != -1) {
							returnStatus = returnStatus.replace(" ", "");
							String[] returnArrays = returnStatus.split(",");
							String status = "";
							if (returnArrays[1].indexOf("\n") != -1) {
								status = returnArrays[1].substring(0, returnArrays[1].indexOf("\n"));
							} else {
								status = returnArrays[1];
							}

							
							if ("0".equals(status.trim())) {
								message = "send success";
								Map<String, Object> smsCode = new HashMap<>();
								smsCode.put("smscode", randomCode);
								aj.setAttributes(smsCode);
								flag = true;
								logger.info(appName + ",短信发送成功，验证码为：" + randomCode);
							} else {
								message = "send fail";
								flag = false;
							}

						}

					} catch (Exception e) {
						// TODO 处理异常
						message = "send false";
						flag = false;
						e.printStackTrace();
					}

				}

			} else {
				message = "cant not find template";
				flag = false;
			}
		} else {
			message = "please send after 60 seconds";
			flag = false;
		}
		aj.setMsg(message);
		aj.setSuccess(flag);
		return aj;

	}

}
